package com.sensePlusVR.main;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sensePlusVR.adapter.MyFragmentPagerAdapter;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.AppVersionInfo;
import com.sensePlusVR.bean.EventBusBean;
import com.sensePlusVR.bean.FeedbackCountRespDto;
import com.sensePlusVR.fragment.AccountFragment;
import com.sensePlusVR.fragment.CollectionFragment;
import com.sensePlusVR.fragment.FollowAFragment;
import com.sensePlusVR.fragment.GameFragment;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.manager.FeedbackManager;
import com.sensePlusVR.utils.AppManager;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.DialogUtils;
import com.sensePlusVR.utils.EventBusUtils;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.VersionUtil;
import com.sensePlusVR.utils.VersionUtil.CheckVersion;
import com.sensePlusVR.widget.MyViewPager;
import com.sensePlusVR.widget.dialog.AppVersionTipDialog;
import com.sensePlusVR.widget.dialog.ModifyPwdDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
//import com.sensePlusVR.activity.listener.CPUInfoListener;
//import com.sensePlusVR.bean.CpuInfo;
//import com.sensePlusVR.utils.MobileParamsDetect;

/**
 * @author: Loren
 * @create: 2016-7-1上午10:36:07
 * @desc: 主 Activity
 */
@SuppressWarnings({"deprecation" })
@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity{

	private static final String TAG = MainActivity.class.getSimpleName();
	private String KEY = this.getClass().getSimpleName();
	public final static String IS_NEW_USER_PARAMETER = "mainis_new_user_parameter";

//	@ViewInject(R.id.navigation_linear)
//	 private View mSearchlayout;

	@ViewInject(R.id.layout)
	private View mLayout; 

//	@ViewInject(R.id.top_title)
//	private TextView top_title;
//	
//	@ViewInject(R.id.main_setting_alarm)
//	private ImageView main_setting_alarm;

	@ViewInject(R.id.vPager)
	private MyViewPager mPager;
	

	@ViewInject(R.id.main_linear_game)
	private LinearLayout main_linear_game;
	@ViewInject(R.id.main_imgbtn_game)
	private ImageView main_imgbtn_game;
	@ViewInject(R.id.main_game_tv)
	private TextView main_game_tv;

	@ViewInject(R.id.main_linear_myGame)
	private LinearLayout main_linear_myGame;
	@ViewInject(R.id.main_imgbtn_myGame)
	private ImageView main_imgbtn_myGame;
	@ViewInject(R.id.main_myGame_tv)
	private TextView main_myGame_tv;

	@ViewInject(R.id.main_linear_follow)
	private LinearLayout main_linear_follow;
	@ViewInject(R.id.main_imgbtn_follow)
	private ImageView main_imgbtn_follow;
	@ViewInject(R.id.main_follow_tv)
	private TextView main_follow_tv;

	@ViewInject(R.id.main_linear_account)
	private LinearLayout main_linear_account;
	@ViewInject(R.id.main_imgbtn_account)
	private ImageView main_imgbtn_account;
	@ViewInject(R.id.main_account_tv)
	private TextView main_account_tv;
	
	@ViewInject(R.id.main_account__new_icon)
	private ImageView main_account__new_icon;

	private MyFragmentPagerAdapter myFragmentPagerAdapter;
	private VRApplication vrApplication;
	
	private Bundle savedInstanceState;
	
	private DataCenter dataCenter;
	
	
	EventListener listener = new EventListener(){
		@Override
		public void Notify(int event, Object data, Object Params) {
			if (Params == null || data == null)
				return;
			MyLog.d(TAG, "event = "+event);
			if (event == FeedbackManager.EventFeedbackNoReadCount){
				FeedbackCountRespDto feedbackCountRespDto = (FeedbackCountRespDto) data;
				MyLog.d(TAG, "listener data : " + feedbackCountRespDto.toString());
				Integer count = feedbackCountRespDto.getCount();
				if(main_account__new_icon == null)return;
				if(count > 0){
					main_account__new_icon.setVisibility(View.VISIBLE);
				}else{
					main_account__new_icon.setVisibility(View.GONE);
				}
			
			}
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.savedInstanceState = savedInstanceState;
		vrApplication = (VRApplication)getApplication();
		dataCenter = DataCenter.getInstans();
		
		MyLog.d(TAG, "onCreate....");
		MyLog.d(TAG, "savedInstanceState="+savedInstanceState);
		MyLog.d(TAG, "Screen width : " + DensityUtil.getScreenWidth(this) + " height : " + DensityUtil.getScreenHeight(this));
		MyLog.d(TAG, "top statusbar height : " + DensityUtil.getStatusBarHeight(this));
		MyLog.d(TAG, "bottom navigatin height ： " + DensityUtil.getNavigationBarHeight(this));
		
		/**
		 * 如果在注册界面没有网络那么只能在MainActivity中显示了
		 */
		boolean isShowCPUInfo = MySharedPreferences.getBoolean2(this,
				MySharedPreferences.NAME_NOT_CLEAR,Constant.IS_FIRST_SHOW_CPUINFO);
		if(!isShowCPUInfo){
			getMobileparamsToTip();
		}
		
		AppVersionInfo newAppVersionInfo = vrApplication.getNewVersionInfo();
		if(newAppVersionInfo!=null){
			checkNewVersion(newAppVersionInfo);
		}
	}
	
	
	public void getMobileparamsToTip() {
		/*
		MobileParamsDetect mobileParamsDetectObj = new MobileParamsDetect();
		String mobileParamsDetect = mobileParamsDetectObj.getPlayLevelHints(this);
		
		if (!mobileParamsDetect.equals(MobileParamsDetect.TIP_ERROR)) {
			MySharedPreferences.save2(this, MySharedPreferences.NAME_NOT_CLEAR,
					Constant.IS_FIRST_SHOW_CPUINFO, true);

			if (!mobileParamsDetect.equals(MobileParamsDetect.TIP_NONE)
					&& mobileParamsDetect.trim() != "") {
				DialogUtils.showConfirmDialogConfirm(MainActivity.this,
						null, mobileParamsDetect,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
			}
		}else{
			mobileParamsDetectObj.setCPUInfoCallback(cpuInfoListener);
		}

		MyLog.d(TAG, "mobileParamsDetect :　" + mobileParamsDetect);
		*/
	}
	
	/*
	private CPUInfoListener cpuInfoListener = new CPUInfoListener() {
		
		@Override
		public void onCPUInfoListener(CpuInfo cpuInfo) {
			MyLog.d(TAG, "cpuInfoListenerFirst cpuInfo : " + cpuInfo);
			getMobileparamsToTip();
			
		}
	};*/


	@Override
	public void setMyContentView() {
		x.view().inject(this);
	}

	@Override
	public void beforeView() {
		super.beforeView();
	}
	


	@Override
	protected void onResume() {
		super.onResume();
		MyLog.d(TAG, "onResume....");
		vrApplication.setCheckVersionCallback(mCheckVersion);
		dataCenter.addFeedbackEventListener(listener, this, KEY);
		dataCenter.getFeedbackNoReadCount();
		EventBus.getDefault().register(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MyLog.d(TAG, "onPause....");
		vrApplication.setCheckVersionCallback(null);
		dataCenter.delFeedbackEventListener(KEY);
		EventBus.getDefault().unregister(this);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		MyLog.d(TAG, "onStop....");
	}
	
	
	
	@Override
	public void initView() {
		super.initView();
		AppManager.getInstance().addActivity(this);
		
		main_linear_game.setOnClickListener(new MyOnClickListener(0));
		main_linear_myGame.setOnClickListener(new MyOnClickListener(1));
		main_linear_follow.setOnClickListener(new MyOnClickListener(2));
		main_linear_account.setOnClickListener(new MyOnClickListener(3));

		main_imgbtn_game.setOnClickListener(new MyOnClickListener(0));
		main_imgbtn_myGame.setOnClickListener(new MyOnClickListener(1));
		main_imgbtn_follow.setOnClickListener(new MyOnClickListener(2));
		main_imgbtn_account.setOnClickListener(new MyOnClickListener(3));

		main_game_tv.setOnClickListener(new MyOnClickListener(0));
		main_myGame_tv.setOnClickListener(new MyOnClickListener(1));
		main_follow_tv.setOnClickListener(new MyOnClickListener(2));
		main_account_tv.setOnClickListener(new MyOnClickListener(3));

		InitViewPager();
		
		//top_title.setText(R.string.main_tab_hot);
		main_imgbtn_game.setImageResource(R.drawable.tab_game_s);
		main_game_tv.setTextColor(getResources().getColor(R.color.main_bottom_nav_text_select));
	}

	private void InitViewPager() {
		ArrayList<Fragment> fragmentsList = new ArrayList<Fragment>();
		GameFragment gameFragment = new GameFragment();
		CollectionFragment collectionFragment = new CollectionFragment();
		//FollowFragment followFragment = new FollowFragment();
		FollowAFragment followAFragment = new FollowAFragment();
		AccountFragment accountFragment = new AccountFragment();
		
		fragmentsList.add(gameFragment);
		fragmentsList.add(collectionFragment);
		fragmentsList.add(followAFragment);
		fragmentsList.add(accountFragment);

		myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList);
		mPager.setAdapter(myFragmentPagerAdapter);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
		mPager.setCurrentItem(0);
		mPager.setNoScroll(true);//屏蔽左右滑动事件.
	}
	
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			Log.d(TAG, "click indext : " + index);
			mPager.setCurrentItem(index);
		}
	};

	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			Log.d(TAG, "onPageSelected index : " + position);
			switch (position) {
			case 0:
				setBackgroundNormal();
				//top_title.setText(R.string.main_tab_hot);
				main_game_tv.setTextColor(getResources().getColor(
						R.color.main_bottom_nav_text_select));
				main_imgbtn_game
						.setImageResource(R.drawable.tab_game_s);
				break;
			case 1:
				setBackgroundNormal();
				//top_title.setText(R.string.main_tab_favorites);
				main_myGame_tv.setTextColor(getResources().getColor(
						R.color.main_bottom_nav_text_select));
				main_imgbtn_myGame
						.setImageResource(R.drawable.tab_my_game_s);
				break;
			case 2:
				setBackgroundNormal();
				//top_title.setText(R.string.main_tab_lovers);
				main_follow_tv.setTextColor(getResources().getColor(
						R.color.main_bottom_nav_text_select));
				main_imgbtn_follow
						.setImageResource(R.drawable.tab_honey_s);
				break;
			case 3:
				setBackgroundNormal();
//				if (main_setting_alarm.getVisibility() == View.GONE)
//					main_setting_alarm.setVisibility(View.VISIBLE);
//				top_title.setText(R.string.main_tab_account);
				main_account_tv.setTextColor(getResources().getColor(
						R.color.main_bottom_nav_text_select));
				main_imgbtn_account
						.setImageResource(R.drawable.tab_my_s);
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	private void setBackgroundNormal() {
		main_imgbtn_game
				.setImageResource(R.drawable.tab_game_n);
		main_imgbtn_myGame
				.setImageResource(R.drawable.tab_my_game_n);
		main_imgbtn_follow
				.setImageResource(R.drawable.tab_honey_n);
		main_imgbtn_account
				.setImageResource(R.drawable.tab_my_n);

		main_game_tv.setTextColor(getResources().getColor(R.color.main_bottom_nav_text_normal));
		main_myGame_tv.setTextColor(getResources().getColor(R.color.main_bottom_nav_text_normal));
		main_follow_tv.setTextColor(getResources().getColor(R.color.main_bottom_nav_text_normal));
		main_account_tv.setTextColor(getResources().getColor(R.color.main_bottom_nav_text_normal));

//		if (main_setting_alarm.getVisibility() == View.VISIBLE)
//			main_setting_alarm.setVisibility(View.GONE);
	}
	
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMessageEvent(EventBusBean event){
		String eventMessage = event.getMessage();
		MyLog.d(TAG, "onMessageEvent : " + eventMessage);
		if(eventMessage.equals(EventBusUtils.EVENT_NOTIFY_FRAGMENT)){
			
			myFragmentPagerAdapter.notifyDataSetChanged();
			
		}
		
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyLog.d(TAG, "onDestroy....");
		//由于当杀死进程后就不会执行生命周期，如果需要退出时候在此处当执行完生命周期后再杀死进程（当点击返回键时设置isExitApp=true）
		if(isExitApp){
			AppManager.getInstance().exitApp(getApplicationContext());
		}
	}
	
	private boolean isExitApp = false;
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		String message = getApplication().getString(R.string.system_alert_quit);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			DialogUtils.showConfirmDialogConfirmCancel(this, getResources()
					.getString(R.string.app_loginout), message,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							AppManager.getInstance().finishActivity();
							isExitApp = true;
							MyLog.d(TAG, "keyback ok");
						}
					}, new DialogInterface.OnClickListener() {// 取消的退出功能
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							MyLog.d(TAG, "keyback cancel");
						}
					});
		}
		return false;
	}

	public void onConfigurationChanged(Configuration newconfig) {
		super.onConfigurationChanged(newconfig);

	}
	
	//版本检查回调
	private CheckVersion mCheckVersion = new CheckVersion() {
			
			@Override
			public void onVersionCallback(AppVersionInfo appVersionInfo) {
				
				if(appVersionInfo!=null){
					
					MyLog.d(TAG, "onVersionCallback : " + appVersionInfo.toString());
			
					checkNewVersion(appVersionInfo);
				}
				
				
			}
	};
	
	
	//检查新版本
	private void checkNewVersion(AppVersionInfo newAppVersionInfo){
		
		String curVersionName = VersionUtil.getVersionName(this);
		String versionCode = newAppVersionInfo.getVersioncode();
		
		if(savedInstanceState==null&&VersionUtil.canVersionUpdate(newAppVersionInfo.getVersonname(), curVersionName)){
			
			MyLog.d(TAG, "versionCode : " + versionCode);
			
			AppVersionTipDialog appVersionTipDlg = null;
			
			if(versionCode.contains("force update")){
				
				MyLog.d(TAG, "force update...");
				
				appVersionTipDlg = new AppVersionTipDialog(this,newAppVersionInfo,false,true);
				
				appVersionTipDlg.show();
				
				return;
				
			}
			
			MyLog.d(TAG, "routine update...");
			
			appVersionTipDlg = new AppVersionTipDialog(this,newAppVersionInfo,true,false);
			
			appVersionTipDlg.show();
			
			appVersionTipDlg.setOnCancelListener(new OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
				
					isModifyPwd();
					
					
				}
			});
			
		}else{
			
			isModifyPwd();
			
		}
	

	}


	private void isModifyPwd() {
		//提示修改密码
		Integer locked = MySharedPreferences.getInteger2(this,
				MySharedPreferences.NAME_NOT_CLEAR,
				Constant.LOGIN_SUCCESS_LOCKED);
		MyLog.d(TAG, "locked : " + locked);
		if (locked == 1) {
		ModifyPwdDialog modifyPwdDialog = new ModifyPwdDialog(this);
		modifyPwdDialog.show();
		}
	}
}
